package com.hbpu.encap.socket.udp;

import java.io.IOException;
import java.net.*;
import java.nio.charset.StandardCharsets;

public class UDPSenderB {
    public static void main(String[] args) throws SocketException, UnknownHostException {
        DatagramSocket datagramSocket = new DatagramSocket(9998);

        byte[] bytes = "hello，明天去吃火锅".getBytes();
        DatagramPacket datagramPacket = new DatagramPacket(bytes, bytes.length, InetAddress.getLocalHost(), 9999);

        try {
            datagramSocket.send(datagramPacket);
            System.out.println("发送成功！");

            try {
                byte[] bytes1 = new byte[1024];
                DatagramPacket datagramPacket2 = new DatagramPacket(bytes1, bytes1.length);
                datagramSocket.receive(datagramPacket2);
                System.out.println("消息接收成功！");
                String s = new String(bytes1, 0, datagramPacket2.getLength(), StandardCharsets.UTF_8);
                System.out.println(s);
            } catch (IOException e) {
                System.out.println("消息接收失败" + e.getMessage());
            }

        } catch (IOException e) {
            System.out.println("发送失败：" + e.getMessage());
        } finally {
            datagramSocket.close();
        }
    }
}
